package alertmanagerdeploylogic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"strings"
	"sync"
	"time"
	"yunzhan/common/models"
	"yunzhan/common/utils"
	"yunzhan/rpc-server/internal/svc"
	agent "yunzhan/rpc-server/pb"
)

type DeployAlertManagerLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeployAlertManagerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeployAlertManagerLogic {
	return &DeployAlertManagerLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// DeployAlertManager 单机部署
func (l *DeployAlertManagerLogic) DeployAlertManager(in *agent.DeployAlertManagerRequest) (*agent.DeployResponse, error) {
	if in.NodeInfo == nil {
		return &agent.DeployResponse{
			Code:    500,
			Message: "未配置节点信息, 无法执行Alertmanager部署",
		}, errors.New("未配置节点信息, 无法执行Alertmanager部署")
	}

	resp := &agent.DeployResponse{
		Code:    200,
		Message: fmt.Sprintf("请求已接收，正在部署 %s 到节点 %s", in.ConfigInfo.ComponentName, in.NodeInfo.Host),
	}

	go l.startDeployment(in)

	return resp, nil
}

func (l *DeployAlertManagerLogic) startDeployment(in *agent.DeployAlertManagerRequest) {

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()

		// 创建 LogManager 实例
		logManager := models.NewLogManager(100, fmt.Sprintf("http://%s:%d", l.svcCtx.Config.RestServices["apiServer"].RestConf.Host, l.svcCtx.Config.RestServices["apiServer"].RestConf.Port))
		defer logManager.Close()
		//
		//flushInterval := 5 * time.Second // 刷新间隔
		//maxBatchSize := 100              // 最大批量大小
		//retryDelay := 2 * time.Second    // 重试延迟
		//maxRetries := 3                  // 最大重试次数
		//
		//// 创建 ComponentInfoManager 实例
		//componentInfoManager := models.NewComponentInfoManager(
		//	1000,
		//	fmt.Sprintf("http://%s:%d", l.svcCtx.Config.RestServices["apiServer"].RestConf.Host, l.svcCtx.Config.RestServices["apiServer"].RestConf.Port),
		//	flushInterval,
		//	maxBatchSize,
		//	retryDelay,
		//	maxRetries)
		//defer componentInfoManager.Close()

		packageDirectory := in.ConfigInfo.PackagePath
		rtrimDir := utils.Rtrim(packageDirectory, "/")
		alertmanagerVersion := in.ConfigInfo.ComponentName
		installPath := utils.Rtrim(in.ConfigInfo.InstallPath, "/")
		baseInfo := fmt.Sprintf("安装包存放目录: %s, Alertmanager version: %s, Alertmanager 安装目录: %s", rtrimDir, alertmanagerVersion, installPath)
		step := 1
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", baseInfo, "Alertmanager", "Server")

		status := true

		checkPathCommand := fmt.Sprintf(`
if [ ! -d "%s" ]; then
   sudo mkdir -p "%s"
fi
`, installPath, installPath)

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "执行组件安装路径检查...", "Alertmanager", "Server")

		output, err := utils.ExecCommand(checkPathCommand)
		if err != nil {
			status = false
			message := fmt.Sprintf("检查组件安装路径异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "检查组件安装路径完成", "Alertmanager", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "解压安装包...", "Alertmanager", "Server")

		tarCommand := fmt.Sprintf("sudo tar -xzf %s/%s -C %s", rtrimDir, alertmanagerVersion, installPath)
		output, err = utils.ExecCommand(tarCommand)
		if err != nil {
			status = false
			message := fmt.Sprintf("解压安装包异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}

		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "解压安装包完成", "Alertmanager", "Server")
		alertmanagerHome := utils.Rtrim(alertmanagerVersion, ".tar.gz")
		home := fmt.Sprintf("%s/%s", installPath, alertmanagerHome)

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "修改组件所属用户组...", "Alertmanager", "Server")

		chownCommand := fmt.Sprintf("sudo chown -R %s:%s %s", in.NodeInfo.Username, in.NodeInfo.Username, home)
		output, err = utils.ExecCommand(chownCommand)
		if err != nil {
			status = false
			message := fmt.Sprintf("修改组件所属用户组异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "修改组件所属用户组完成", "Alertmanager", "Server")

		checkPathCommand = fmt.Sprintf(`
if [ ! -d "%s" ]; then
   sudo mkdir -p "%s"
fi
sudo chown -R %s:%s %s
`, in.AlertManagerConfig.StoragePath, in.AlertManagerConfig.StoragePath, in.NodeInfo.Username, in.NodeInfo.Username, in.AlertManagerConfig.StoragePath)

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "检查组件数据存储目录...", "Alertmanager", "Server")

		output, err = utils.ExecCommand(checkPathCommand)
		if err != nil {
			status = false
			message := fmt.Sprintf("检查组件数据存储目录异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "检查组件数据存储目录完成", "Alertmanager", "Server")

		alertmanagerServiceFile := fmt.Sprintf(`[Unit]
Description=Prometheus Alertmanager Service
After=network.target
 
[Service]
Type=simple
User=%s
Group=%s
ExecStart=%s/alertmanager \
 --config.file=%s/alertmanager.yml \
 --storage.path="%s" \
 --data.retention=%s \
 --web.listen-address=%s \
 --log.level=debug

ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=655355
LimitNPROC=655355
Restart=on-failure
KillMode=process

[Install]
WantedBy=multi-user.target`,
			in.NodeInfo.Username,
			in.NodeInfo.Username,
			home,
			home,
			in.AlertManagerConfig.StoragePath,
			in.AlertManagerConfig.DataRetention,
			in.AlertManagerConfig.WebListenAddress)

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "创建alertmanager.service文件...", "Alertmanager", "Server")

		writeServiceFileCommand := fmt.Sprintf("echo '%s' | sudo tee /etc/systemd/system/alertmanager.service", alertmanagerServiceFile)
		output, err = utils.ExecCommand(writeServiceFileCommand)
		if err != nil {
			status = false
			message := fmt.Sprintf("创建alertmanager_logic.service文件异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "创建alertmanager.service文件完成", "Alertmanager", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "启动AlertManager服务...", "Alertmanager", "Server")
		step++
		reloadSystemdCommand := fmt.Sprintf("sudo systemctl daemon-reload && sudo systemctl enable alertmanager.service --now")
		output, err = utils.ExecCommand(reloadSystemdCommand)
		if err != nil {
			status = false
			message := fmt.Sprintf("启动Alertmanager服务异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}

		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "启动Alertmanager服务完成", "Alertmanager", "Server")
		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "等待Alertmanager服务完全启动", "Alertmanager", "Server")

		time.Sleep(5 * time.Second)

		step++
		statusCommand := "sudo systemctl is-active alertmanager.service"
		output, err = utils.ExecCommand(statusCommand)
		if err != nil || strings.TrimSpace(output) != "active" {
			status = false
			message := fmt.Sprintf("Alertmanager启动后未正常运行: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}

		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "Alertmanager部署成功", "Alertmanager", "Server")

		// 获取当前主机信息
		currentIP, currentIPErr := utils.GetCurrentInternalIP()
		if currentIPErr != nil {
			message := fmt.Sprintf("%s: 无法获取当前主机IP: %v", in.NodeInfo.Host, currentIPErr)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}
		currentHost, currentHostErr := utils.GetCurrentHostname()
		if currentHostErr != nil {
			message := fmt.Sprintf("%s: 无法获取当前主机名: %v", in.NodeInfo.Host, currentHostErr)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Alertmanager", "Server")
			return
		}

		alertmanagerInfo := &models.ComponentInfo{
			ClusterID:      in.ClusterID,
			ComponentName:  "Alertmanager",
			Version:        in.Version,
			NodeHost:       currentHost,
			NodeIP:         currentIP,
			ComponentRole:  "Server",
			HomePath:       home,
			DataStorageDir: in.AlertManagerConfig.StoragePath,
			Port:           in.AlertManagerConfig.WebListenAddress,
			Status:         status,
			AdditionalInfo: fmt.Sprintf("config_file=%s/alertmanager.yml", home),
		}

		l.svcCtx.ComponentInfoManager.SendComponentInfo(alertmanagerInfo)

	}()
	wg.Wait()

}
